package com.wisewin.circle.service;

import com.alibaba.fastjson.JSON;
import com.wisewin.circle.config.dto.ResultDTO;
import com.wisewin.circle.config.dto.ResultDTOBuilder;
import com.wisewin.circle.dao.*;
import com.wisewin.circle.entity.bo.QueryParamBO;
import com.wisewin.circle.entity.db.*;
import com.wisewin.circle.util.DateUtil;
import com.wisewin.circle.util.PageInfo;
import com.wisewin.circle.util.PageObjectUtil;
import com.wisewin.circle.util.PageUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.*;

@Service
@Transactional
public class TrendService {

    @Autowired
    private CircleDAO circleDAO;
    @Autowired
    private TrendDAO trendDAO;
    @Autowired
    private TrendCommentDAO trendCommentDAO;
    @Autowired
    private TrendCommentHeartDAO trendCommentHeartDAO;
    @Autowired
    private TrendVisitDAO trendVisitDAO;

    // 动态详情
    public ResultDTO queryTrendDetail(Integer trendId, Integer userId){
        if (trendId == null) {
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        // 判断动态是否存在
        TrendDO trendDO = trendDAO.queryTrendDetail(trendId, userId);
        if(trendDO == null){
            return ResultDTOBuilder.failure("1", "动态不存在", null);
        }
        if(!StringUtils.isEmpty(trendDO.getTrendUrl())){
            trendDO.setLstTrendUrl(Arrays.asList(trendDO.getTrendUrl().split(",")));
        }
        // 处理时间
        String trendTime = DateUtil.convertTimeToFormat(trendDO.getCreateTime().getTime());
        trendDO.setTrendTime(trendTime);
        // 不是本人访问，添加访问记录
        TrendVisitDO trendVisitDO = new TrendVisitDO();
        trendVisitDO.setUserId(userId);
        trendVisitDO.setTrendId(trendId);
        trendVisitDAO.insert(trendVisitDO);
        trendDAO.updateVisitNum(trendId);
        return ResultDTOBuilder.success(trendDO);
    }

    // 查询评论列表
    public ResultDTO queryTrendCommentList(QueryParamBO queryParamBO){
        if(queryParamBO.getTrendId() == null){
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        // 判断动态是否存在
        TrendDO trendDO = trendDAO.queryTrendById(queryParamBO.getTrendId());
        if(trendDO == null){
            return ResultDTOBuilder.failure("1", "动态不存在", null);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", queryParamBO.getUserId());
        map.put("trendId", queryParamBO.getTrendId());
        List<TrendCommentDO> lstComment = trendCommentDAO.queryTrendCommentList(map);
        if(!CollectionUtils.isEmpty(lstComment)){
            for(TrendCommentDO trendCommentDO : lstComment){
                if(!StringUtils.isEmpty(trendCommentDO.getContentUrl())){
                    trendCommentDO.setLstContentUrl(Arrays.asList(trendCommentDO.getContentUrl().split(",")));
                }
                // 处理时间
                String commentTime = DateUtil.convertTimeToFormat(trendCommentDO.getCreateTime().getTime());
                trendCommentDO.setCommentTime(commentTime);
            }
            // 处理数据
            TrendCommentNodeBuilder menuTree = new TrendCommentNodeBuilder(lstComment);
            lstComment = menuTree.builTree();
        }
        return ResultDTOBuilder.success(lstComment);
    }

    // 取消动态评论点赞
    public ResultDTO cancleTrendCommentHeart(TrendCommentHeartDO trendCommentHeartDO){
        if(trendCommentHeartDO.getCommentId() == null){
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        // 查询评论是否存在
        TrendCommentDO trendCommentDO = trendCommentDAO.queryTrendCommentById(trendCommentHeartDO.getCommentId());
        if(trendCommentDO == null){
            return ResultDTOBuilder.failure("1", "当前评论不存在", null);
        }
        // 判断是否已经点赞
        TrendCommentHeartDO trendCommentHeartOld = trendCommentHeartDAO.queryTrendCommentHeartById(trendCommentHeartDO.getUserId(),
                trendCommentHeartDO.getCommentId());
        if(trendCommentHeartOld == null){
            return ResultDTOBuilder.failure("1", "未点赞", null);
        }
        // 删除点赞
        trendCommentHeartDAO.delete(trendCommentHeartDO.getUserId(), trendCommentHeartDO.getCommentId());
        // 修改点赞次数
        trendCommentDAO.cancleHeartNum(trendCommentHeartDO.getCommentId());
        return ResultDTOBuilder.success(null);
    }

    // 添加动态评论点赞
    public ResultDTO addTrendCommentHeart(TrendCommentHeartDO trendCommentHeartDO){
        if(trendCommentHeartDO.getCommentId() == null){
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        // 查询评论是否存在
        TrendCommentDO trendCommentDO = trendCommentDAO.queryTrendCommentById(trendCommentHeartDO.getCommentId());
        if(trendCommentDO == null){
            return ResultDTOBuilder.failure("1", "当前评论不存在", null);
        }
        // 判断是否已经点赞
        TrendCommentHeartDO trendCommentHeartOld = trendCommentHeartDAO.queryTrendCommentHeartById(trendCommentHeartDO.getUserId(),
                trendCommentHeartDO.getCommentId());
        if(trendCommentHeartOld != null){
            return ResultDTOBuilder.failure("1", "已点赞", null);
        }
        // 添加评论点赞
        trendCommentHeartDAO.insert(trendCommentHeartDO);
        // 修改评论点赞次数
        trendCommentDAO.updateHeartNum(trendCommentHeartDO.getCommentId());
        return ResultDTOBuilder.success(null);
    }

    // 删除动态评论
    public ResultDTO deleteTrendComment(TrendCommentDO trendCommentDO){
        if(trendCommentDO.getCommentId() == null){
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        // 查询评论是否存在
        TrendCommentDO trendCommentOld = trendCommentDAO.queryTrendCommentById(trendCommentDO.getCommentId());
        if(trendCommentOld == null){
            return ResultDTOBuilder.failure("1", "当前评论不存在", null);
        }
        // 删除评论
        trendCommentDAO.delete(trendCommentDO.getCommentId());
        // 修改评论次数
        trendDAO.cancleCommentNum(trendCommentOld.getTrendId());
        return ResultDTOBuilder.success(null);
    }

    // 添加动态评论
    public ResultDTO addTrendComment(TrendCommentDO trendCommentDO){
        Integer parentId = trendCommentDO.getParentId() == null ? 0 : trendCommentDO.getParentId();
        trendCommentDO.setParentId(parentId);
        if(trendCommentDO.getTrendId() == null || trendCommentDO.getAcceptUserId() == null){
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        if(StringUtils.isEmpty(trendCommentDO.getContent())){
            return ResultDTOBuilder.failure("1", "请填写评论内容", null);
        }
        // 查询活动
        TrendDO trendOld = trendDAO.queryTrendById(trendCommentDO.getTrendId());
        if(trendOld == null){
            return ResultDTOBuilder.failure("1", "活动不存在", null);
        }
        // 添加动态评论信息
        trendCommentDAO.insert(trendCommentDO);
        // 添加动态评论数量
        trendDAO.updateCommentNum(trendCommentDO.getTrendId());
        return ResultDTOBuilder.success(null);
    }

    // 查询我的动态列表
    public ResultDTO queryMyTrendList(Integer userId, Integer loginUserId){
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("loginUserId", loginUserId);
        // 查询年份
        List<String> lstYear = trendDAO.queryTrendYear(map);
        // 查询动态
        List<TrendDO> lstTrend = trendDAO.queryMyTrendList(map);
        if(CollectionUtils.isEmpty(lstYear) || CollectionUtils.isEmpty(lstTrend)){
            return ResultDTOBuilder.success(null);
        }
        List<Map<String, Object>> lstResult = new ArrayList<>();
        for(String yearThis : lstYear){
            List<TrendDO> lstTrendYear = new ArrayList<>();
            for(TrendDO trendDO : lstTrend){
                // 是否关注
                Integer ifFollow = trendDO.getUserId() == loginUserId ? 1 : trendDO.getIfFollow();
                // 是否可取消关注
                Integer ifCanCancle = trendDO.getUserId() == loginUserId ? 0 : 1;
                trendDO.setIfFollow(ifFollow);
                trendDO.setIfCanCancle(ifCanCancle);
                // 处理图片地址
                if(!StringUtils.isEmpty(trendDO.getTrendUrl())){
                    trendDO.setLstTrendUrl(Arrays.asList(trendDO.getTrendUrl().split(",")));
                }
                // 处理时间
                String trendTime = DateUtil.convertTimeToFormat(trendDO.getCreateTime().getTime());
                trendDO.setTrendTime(trendTime);
                // 处理年月日
                String year = DateUtil.formatDate(trendDO.getCreateTime(), "yyyy");
                String month = Integer.parseInt(DateUtil.formatDate(trendDO.getCreateTime(), "MM")) + "月";
                String day = DateUtil.formatDate(trendDO.getCreateTime(), "dd");
                trendDO.setYear(year);
                trendDO.setMonth(month);
                trendDO.setDay(day);
                // 判断年限
                if(yearThis.equals(year)){
                    lstTrendYear.add(trendDO);
                }
            }
            Map<String, Object> result = new HashMap<>();
            result.put("year", yearThis);
            result.put("lstTrend", lstTrendYear);
            lstResult.add(result);
        }
        return ResultDTOBuilder.success(lstResult);
    }

    // 查询动态列表
    public ResultDTO queryTrendList(QueryParamBO queryParamBO, PageUtil pageUtil){
        Map<String, Object> map = new HashMap<>();
        map.put("userId", queryParamBO.getUserId());
        map.put("circleId", queryParamBO.getCircleId());
        map.put("ifSelf", queryParamBO.getIfSelf());
        map.put("type", queryParamBO.getType());
        map.put("ifRelation", queryParamBO.getIfRelation());
        map.put("pageOffset", pageUtil.getPageNo());
        map.put("pageSize", pageUtil.getPageSize());
        PageObjectUtil page = new PageObjectUtil();
        PageInfo pageData = page.savePageObject(trendDAO.queryTrendCount(map), trendDAO.queryTrendList(map), pageUtil);
        if (pageData == null || CollectionUtils.isEmpty(pageData.getRecords())) {
            return ResultDTOBuilder.success(pageData);
        }
        for(TrendDO trendDO : (List<TrendDO>)pageData.getRecords()){
            // 是否关注
            Integer ifFollow = trendDO.getUserId() == queryParamBO.getUserId() ? 1 : trendDO.getIfFollow();
            // 是否可取消关注
            Integer ifCanCancle = trendDO.getUserId() == queryParamBO.getUserId() ? 0 : 1;
            trendDO.setIfFollow(ifFollow);
            trendDO.setIfCanCancle(ifCanCancle);
            // 处理图片地址
            if(!StringUtils.isEmpty(trendDO.getTrendUrl())){
                trendDO.setLstTrendUrl(Arrays.asList(trendDO.getTrendUrl().split(",")));
            }
            // 处理时间
            String trendTime = DateUtil.convertTimeToFormat(trendDO.getCreateTime().getTime());
            trendDO.setTrendTime(trendTime);
        }
        return ResultDTOBuilder.success(pageData);
    }

    // 查询我的点赞收藏列表
    public ResultDTO queryMyTrendHeartList(QueryParamBO queryParamBO, PageUtil pageUtil){
        Map<String, Object> map = new HashMap<>();
        map.put("userId", queryParamBO.getUserId());
        map.put("pageOffset", pageUtil.getPageNo());
        map.put("pageSize", pageUtil.getPageSize());
        PageObjectUtil page = new PageObjectUtil();
        PageInfo pageData = page.savePageObject(trendDAO.queryMyTrendHeartCount(map), trendDAO.queryMyTrendHeartList(map), pageUtil);
        if (pageData == null || CollectionUtils.isEmpty(pageData.getRecords())) {
            return ResultDTOBuilder.success(pageData);
        }
        // 处理数据
        for(TrendDO trendDO : (List<TrendDO>)pageData.getRecords()){
            // 是否关注
            Integer ifFollow = trendDO.getUserId() == queryParamBO.getUserId() ? 1 : trendDO.getIfFollow();
            // 是否可取消关注
            Integer ifCanCancle = trendDO.getUserId() == queryParamBO.getUserId() ? 0 : 1;
            trendDO.setIfFollow(ifFollow);
            trendDO.setIfCanCancle(ifCanCancle);
            trendDO.setIfHeart(1);
            // 处理图片地址
            if(!StringUtils.isEmpty(trendDO.getTrendUrl())){
                trendDO.setLstTrendUrl(Arrays.asList(trendDO.getTrendUrl().split(",")));
            }
            // 处理时间
            String trendTime = DateUtil.convertTimeToFormat(trendDO.getCreateTime().getTime());
            trendDO.setTrendTime(trendTime);
        }
        return ResultDTOBuilder.success(pageData);
    }

    // 删除动态
    public ResultDTO deleteTrend(TrendDO trendDO){
        if(trendDO.getTrendId() == null){
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        TrendDO trendOld = trendDAO.queryTrendById(trendDO.getTrendId());
        if(trendOld == null || trendOld.getStatus() == ActivityDO.STATUS_YSC){
            return ResultDTOBuilder.failure("1", "动态不存在或者已删除", null);
        }
        // 删除动态
        trendDAO.updateStatus(trendDO.getTrendId(), ActivityDO.STATUS_YSC);
        // 修改圈子动态数量
        if(trendOld.getCircleId() != null){
            circleDAO.updateTrendNumJs(trendOld.getCircleId());
        }
        return ResultDTOBuilder.success(trendDO);
    }

    // 添加动态
    public ResultDTO addTrend(TrendDO trendDO){
        if(StringUtils.isEmpty(trendDO.getTrendUrl())){
            return ResultDTOBuilder.failure("1", "请上传动态图片", null);
        }
        if(StringUtils.isEmpty(trendDO.getContent())){
            return ResultDTOBuilder.failure("1", "请填写分享内容", null);
        }
        // 判断圈子是否存在
        if(trendDO.getCircleId() != null){
            CircleDO circleDO = circleDAO.queryCircleById(trendDO.getCircleId());
            if(circleDO == null){
                return ResultDTOBuilder.failure("1", "圈子不存在", null);
            }
        }
        // 添加动态
        trendDO.setStatus(ActivityDO.STATUS_YFB);
        trendDAO.insert(trendDO);
        // 处理圈子动态数量
        if(trendDO.getCircleId() != null){
            circleDAO.updateTrendNum(trendDO.getCircleId());
        }
        return ResultDTOBuilder.success(trendDO);
    }
}
